<?php

namespace app\api\controller;

use app\payment\PayFactory;
use app\services\GoodsCommentService;
use app\services\OrderCommentService;
use app\services\OrderRefundService;
use app\services\OrderService;
use app\services\PaymentService;
use app\services\UserCouponService;
use plugin\admin\app\model\Option;
use plugin\admin\app\model\Order;
use support\Db;
use support\Request;

class OrderController
{
    public function checkCanPreview(Request $request)
    {
        $data = $request->post();

        try {
            OrderService::checkCanBuy($data);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }

    public function preview(Request $request)
    {
        $data = $request->post();

        try {
            return ok_rsp('成功', OrderService::preview($data));
        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }

    public function noticeShipping(Request $request)
    {
        try {
            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }
    public function cancel(Request $request)
    {
        $data = $request->post();

        Db::beginTransaction();
        try {

            if (empty($data['order_no'])) {
                throw new \Exception('订单号不能为空');
            }

            OrderService::cancel($data['order_no'], $data['cancel_reason'] ?? '');

            Db::commit();
            return ok_rsp('成功');
        } catch (\Exception $e) {
            Db::rollBack();
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }

    public function delete(Request $request)
    {
        try {
            $orderNo = $request->post('order_no');

            OrderService::delete($orderNo);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function changePayWay(Request $request)
    {
        try {
            $orderNo = $request->post('order_no');
            $payWay = $request->post('pay_way');

            OrderService::changePayWay($orderNo, $payWay);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function create(Request $request)
    {
        $data = $request->post();

        Db::beginTransaction();
        try {

            $data['pay_way_type'] = $data['pay_way_type'] ?? 'mini';
            $orderNo = OrderService::create($data);

            Db::commit();
            return ok_rsp('成功', ['order_no' => $orderNo]);
        } catch (\Exception $e) {
            Db::rollBack();
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }

    public function orderShippingNotice(Request $request)
    {
        try {
            $orderNo = $request->post('order_no');

            OrderService::noticeShipping($orderNo);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function pay(Request $request)
    {
        $data = $request->post();

        Db::beginTransaction();
        try {
            if (!isset($data['order_no'])) {
                throw new \Exception('订单号不能为空');
            }

            $order = Order::where('order_no', $data['order_no'])->first();

            if (!$order) {
                throw new \Exception('不存在的订单');
            }

            if (PaymentService::needCheckPaymentPassword($order['pay_way'])) {
                PaymentService::checkPayPassword($request->post('pay_password'));
            }

            if (empty($data['order_no'])) {
                throw new \Exception('订单号不能为空');
            }

            [$orderNo, $payResult] = OrderService::pay($data['order_no']);

            Db::commit();
            return ok_rsp('成功', ['order_no' => $orderNo, 'pay_result' => $payResult]);
        } catch (\Exception $e) {
            Db::rollBack();
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }

    public function couponList(Request $request)
    {
        try {
            $cartItemIds = $request->post('cart_item_ids');
            $data = UserCouponService::getOrderCouponList($cartItemIds);
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function cancelReasonList()
    {
        try {
            $item = Option::where('name', "dict_order_cancel_reason")->first();
            $values = json_decode($item['value'], true);
            $values = array_column($values, 'value');
            return ok_rsp('成功', $values);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function list(Request $request)
    {
        $page = $request->post('page', 1);
        $status = $request->post('status', 0);
        $keyword = $request->post('keyword', '');

        try {

            $list = OrderService::list($page, 10, $status, $keyword);

            return ok_rsp('成功', $list);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function supportPayWay(Request $request)
    {
        try {
            $list = OrderService::supportPayWay();

            return ok_rsp('成功', $list);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function detail(Request $request)
    {
        $data = $request->post();

        try {
            if (!isset($data['order_no'])) {
                throw new \Exception('订单号不能为空');
            }

            $list = OrderService::detail($data['order_no']);

            return ok_rsp('成功', $list);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function expressList(Request $request)
    {
        $orderNo = $request->post('order_no');

        try {

            $list = OrderService::expressList($orderNo);

            return ok_rsp('成功', $list);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function refundExpressList(Request $request)
    {
        $orderNo = $request->post('order_no');

        try {

            $list = OrderService::refundExpressList($orderNo);

            return ok_rsp('成功', $list);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function confirm(Request $request)
    {
        $data = $request->post();

        try {
            if (empty($data['order_no'])) {
                throw new \Exception('订单编号不能为空');
            }

            OrderService::confirm($data);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function payShipping(Request $request)
    {
        $orderNo = $request->post('order_no');
        $payWay = $request->post('pay_way', PayFactory::BALANCE);
        $couponId = $request->post('coupon_id', 0);

        Db::beginTransaction();

        try {
            if (empty($orderNo)) {
                throw new \Exception('订单编号不能为空');
            }

            echo $payWay;
            OrderService::createShippingFeeOrder([
                'order_no' => $orderNo,
                'pay_way' => $payWay,
                'coupon_id' => $couponId
            ]);

            Db::commit();
            return ok_rsp('成功');
        } catch (\Exception $e) {
            Db::rollBack();
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }

    public function comment(Request $request)
    {
        $data = $request->post();

        Db::beginTransaction();
        try {
            $orderNo = $request->post('order_no');
            $comments = $data['comments'] ?? [];
            $anonymous = $data['anonymous'] ?? 0;

            if (!$orderNo) {
                throw new \Exception('订单号不能为空');
            }

            foreach ($comments as $comment) {
                if (empty($comment['goods_id'])) {
                    throw new \Exception('商品ID不能为空');
                }

                if (empty($comment['desc'])) {
                    throw new \Exception('评价内容不能为空');
                }

                if (empty($comment['thumbs']) || (!is_array($comment['thumbs']) && count($comment['thumbs']) == 0)) {
                    throw new \Exception('评价图片不能为空');
                }

                if (empty($comment['service'])) {
                    throw new \Exception('请评价服务态度');
                }
            }

            GoodsCommentService::comment($orderNo, $comments, $anonymous);

            Db::commit();

            return ok_rsp('成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return err_rsp($e->getMessage());
        }
    }

    public function checkCode(Request $request)
    {
        $data = $request->post();

        try {
            if (empty($data['check_code'])) {
                throw new \Exception('核销码不能为空');
            }

            OrderService::checkCode($data);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function orderQrCode(Request $request)
    {
        try {
            $orderNo = $request->post('order_no');

            return response(OrderService::qrcode($orderNo))->header('content-type', 'image/jpeg');

        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function applyRefund(Request $request)
    {
        $data = $request->post();

        try {
            if (empty($data['order_no'])) {
                throw new \Exception('订单编号不能为空');
            }

            OrderRefundService::add($data);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function refundList(Request $request)
    {
        $page = $request->post('page', 1);
        $length = $request->post('length', 10);
        $status = $request->post('status', 0);

        try {
            $data = OrderService::refundList($page, $length, $status);

            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function cancelRefund(Request $request)
    {
        $data = $request->post();

        try {
            if (empty($data['order_no'])) {
                throw new \Exception('订单编号不能为空');
            }

            OrderRefundService::cancel($data);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function refundDetail(Request $request)
    {
        $data = $request->post();

        try {
            if (empty($data['order_no'])) {
                throw new \Exception('订单编号不能为空');
            }

            $data = OrderService::refundDetail($data);

            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function setRefundExpress(Request $request)
    {
        $data = $request->post();

        try {
            if (empty($data['order_no'])) {
                throw new \Exception('订单编号不能为空');
            }

            OrderRefundService::setRefundExpress($data['order_no'], $data['express_no'], $data['express_company']);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function refundHistory(Request $request)
    {
        $data = $request->post();

        try {
            if (empty($data['order_no'])) {
                throw new \Exception('订单编号不能为空');
            }

            $data = OrderService::refundHistory($data);

            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }
}